import { _decorator, Asset, Component, Vec3 } from 'cc';
import { ANIM_TIMES, AnimAction } from '../actions/AnimAction';
import { AttackAction } from '../actions/AttackAction';
import { WalkAction } from '../actions/WalkAction';
import { Hero } from '../model/Hero';
import { ResourceMgr } from '../../manager/ResourceMgr';
const { ccclass, property } = _decorator;


/**
 * 移动组件
 * 
 * 控制角色的移动与行走
 */
@ccclass('HeroCtrl')
export class HeroCtrl extends Component {

    private animAction: AnimAction
    private attackAction: AttackAction
    private walkAction: WalkAction

    private hero: Hero

    public async init(hero: Hero) {
        this.hero = hero;
        // 动画组件
        let resource: Asset[] = await ResourceMgr.Instance.loadDir("/heros/" + hero.resId + "/bones")
        this.animAction = this.node.addComponent(AnimAction)
        this.animAction.init(this.node.getChildByPath("Bones"), hero.animType, resource)
        // 攻击组件
        this.attackAction = this.node.addComponent(AttackAction)
        this.attackAction.init()
        // 行走组件
        this.walkAction = this.node.addComponent(WalkAction)
        this.walkAction.init()
    }

    /**
     * 攻击
     * @param target 攻击目标
     */
    onAttack(target: HeroCtrl) {
        console.info("开始攻击")
        let canAttack = this.attackAction.canAttack(0.4, () => {
            console.info("开始计算掉血")
            target.onHurt(10);
        })
        if (canAttack) {
            this.animAction.setState(this.hero.attackAnim, ANIM_TIMES.ONCE, () => {
                console.info('攻击动画结束')
                this.animAction.setState(this.hero.restAnim, ANIM_TIMES.FOREVER)
            })
        }
    }

    /**
     * 受伤
     * @param atk 伤害值 
     */
    onHurt(atk: number) {
        console.info("受伤了,血量-" + atk)
    }

    /**
     * 
     * @param targetPos 目标地址
     */
    onWalk(targetPos: Vec3) {
        let canWalk = this.walkAction.canWalk(targetPos, () => {
            console.info('跑到目标位置')
            this.animAction.setState(this.hero.restAnim, ANIM_TIMES.FOREVER)
        })
        if (canWalk) {
            this.animAction.setState(this.hero.walkAnim, ANIM_TIMES.FOREVER)
        }
    }

}